package com.feeyo.groundservice.recordnfc.activity.view

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableLongState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ScreenUtils
import com.feeyo.groundservice.base_util.CallbackWithData
import com.feeyo.groundservice.base_util.FyLog
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.dealString
import com.feeyo.groundservice.base_util.formatTimeYMDHM
import com.feeyo.groundservice.base_util.getConfirmDlg
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.composewidget.util.EmptyListView
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.pxToDp
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.constant.ComposePosition
import com.feeyo.groundservice.composewidget.view.edit.RoundedCornerOutlinedTextField
import com.feeyo.groundservice.composewidget.view.refreshlayout.PullToRefreshLayout
import com.feeyo.groundservice.composewidget.view.refreshlayout.rememberRefreshLayoutState
import com.feeyo.groundservice.composewidget.view.sidemenu.ChainScrollableComponentState
import com.feeyo.groundservice.composewidget.view.sidemenu.SlideMenu
import com.feeyo.groundservice.composewidget.view.title_bar.CommonTitleView
import com.feeyo.groundservice.composewidget.view.util.VerticalSpace
import com.feeyo.groundservice.recordnfc.R
import com.feeyo.groundservice.recordnfc.base.refreshState
import com.feeyo.groundservice.recordnfc.constant.AttachResourceType
import com.feeyo.groundservice.recordnfc.constant.RecorderType
import com.feeyo.groundservice.recordnfc.constant.ResourceType
import com.feeyo.groundservice.recordnfc.constant.statusBarColor
import com.feeyo.groundservice.recordnfc.model.NfcBindItemBO
import com.feeyo.groundservice.recordnfc.model.TaskItemBO
import com.feeyo.groundservice.recordnfc.viewmodel.RecorderCardViewModel
import kotlin.math.min

/**
 *作者：70893 on 2025-10-15
 *描述：
 */

@Composable
fun SearchMainView() {

    val searchKey = remember { mutableStateOf("") }
    val refreshFlag = remember { mutableLongStateOf(System.currentTimeMillis()) }
    val viewModel: RecorderCardViewModel = viewModel()
    //侧滑状态
    val states = remember { mutableStateListOf<ChainScrollableComponentState>() }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {

        CommonTitleView(
            "",
            bg = statusBarColor.toComposeColor(),
            topPadding = BarUtils.getStatusBarHeight(),
            titleContent = {
                RoundedCornerOutlinedTextField(
                    modifier = Modifier.fillMaxWidth(0.7f).height(R.dimen.d36.dimenToDp()),
                    onValueChange = {
                        searchKey.value = it
                        //清空时自动刷新
                        if (searchKey.value.isEmpty()) {
                            refreshFlag.longValue = System.currentTimeMillis()
                        }
                    },
                    cornerRadius = R.dimen.d22.dimenToDp(),
                    focusedContainerColor = R.color.white.toComposeColor(),
                    unfocusedContainerColor = R.color.white.toComposeColor(),
                    hint = "请输入NFC卡号、姓名、车牌号、任务名称、位置",
                    cursorColor = statusBarColor.toComposeColor(),
                    hasLeadingIcon = true,
                    horizontalPadding = R.dimen.d10.dimenToDp()
                )
            },
            onBack = {
                ActivityUtils.getTopActivity()?.finish()
            },
            rightContent = {
                if (searchKey.value.isNotEmpty()) {
                    Text(
                        text = "搜索",
                        fontSize = R.dimen.d15.dimenToSp(),
                        fontWeight = FontWeight.W500,
                        color = R.color.white.toComposeColor(),
                        modifier = Modifier.intervalClick {
                            refreshFlag.longValue = System.currentTimeMillis()
                        }
                    )
                }
            }
        )

        val logs = viewModel.nfcBindList.value ?: emptyList()
        //列表
        PullToRefreshLayout(
            modifier = Modifier.fillMaxSize(),
            refreshLayoutState = rememberRefreshLayoutState {
                //编写刷新逻辑
                refreshState = this
                refreshFlag.longValue = System.currentTimeMillis()
            }
        ) {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(R.dimen.d5.dimenToDp())
            ) {
                item {
                    VerticalSpace(R.dimen.d1.dimenToDp())
                }
                if (logs.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier.fillMaxWidth().height(R.dimen.d200.dimenToDp())
                                .background(R.color.white.toComposeColor()),
                            contentAlignment = Alignment.Center
                        ) {
                            EmptyListView()
                        }
                    }
                } else {
                    items(logs, key = { it.id }) { item ->
                        SearchItemView(
                            item,
                            onOpenClose = { state ->
                                //遍历state，把不是自己的都复原
                                states.forEach {
                                    if (it != state) {
                                        it.setScrollPositionWithAnimate(it.maxPx)
                                    }
                                }
                            },
                            onBackGround = { state, menuWidth ->
                                states.add(state)
                                Box(
                                    modifier = Modifier.width(menuWidth).fillMaxHeight()
                                        .background(
                                            color = R.color.red_FF3141.toComposeColor()
                                        )
                                        .intervalClick {
                                            state.closeMenu()
                                            //加任务
                                            appendTask(
                                                viewModel = viewModel,
                                                filterTask = logs.filter { it.nfc == item.nfc }
                                                    .map { it.long_id },
                                                item = item,
                                                onSuccess = {
                                                    refreshFlag.longValue =
                                                        System.currentTimeMillis()
                                                }
                                            )
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = "加任务",
                                        fontSize = R.dimen.d14.dimenToSp(),
                                        color = R.color.white.toComposeColor(),
                                    )
                                }
                            },
                            refreshFlag = refreshFlag
                        )
                    }
                }
                item {
                    VerticalSpace(R.dimen.d1.dimenToDp())
                }
            }
        }
    }

    LaunchedEffect(key1 = refreshFlag.longValue) {
        viewModel.getNfcBind(searchKey.value)
    }
}


@Composable
private fun SearchItemView(
    item: NfcBindItemBO,
    onOpenClose: (ChainScrollableComponentState) -> Unit,
    onBackGround: @Composable (ChainScrollableComponentState, Dp) -> Unit,
    refreshFlag: MutableLongState,
) {
    Card(
        modifier = Modifier
            .width(ScreenUtils.getScreenWidth().pxToDp())
            .padding(horizontal = R.dimen.d15.dimenToDp()),
        elevation = CardDefaults.elevatedCardElevation(defaultElevation = R.dimen.d5.dimenToDp()),
        shape = RoundedCornerShape(R.dimen.d4.dimenToDp()),
        colors = CardDefaults.elevatedCardColors(containerColor = R.color.white.toComposeColor())
    ) {
        val menuWidth = if (item.nfc_type == RecorderType.TASK.type)
            R.dimen.d50.dimenToDp() else 0.dp

        SlideMenu(
            minScrollPosition = 0.dp,
            maxScrollPosition = menuWidth,
            contentIsMove = false,
            composePosition = ComposePosition.End,
            modifier = Modifier.fillMaxWidth(),
            onOpenOrClose = {
                onOpenClose(it)
            },
            backgroundContent = {
                onBackGround(it, menuWidth)
            }
        ) {
            Column(
                modifier = Modifier.fillMaxWidth().padding(R.dimen.d10.dimenToDp())
                    .intervalClick {
                        it.closeMenu()
                        showDetail(item, refreshFlag)
                    }
            ) {
                val title = when (item.nfc_type) {
                    RecorderType.PERSON.type -> item.personName
                    RecorderType.CAR.type -> item.carNum
                    RecorderType.TASK.type -> item.taskName
                    else -> ""
                }
                Text(
                    text = title.dealString(),
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W400,
                    color = R.color.black_33.toComposeColor(),
                )

                if (item.nfc_type == RecorderType.TASK.type) {
                    VerticalSpace(R.dimen.d5.dimenToDp())
                    Text(
                        text = item.taskLinkName.dealString(),
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W400,
                        color = R.color.black_33.toComposeColor(),
                    )
                }

                VerticalSpace(R.dimen.d5.dimenToDp())
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = item.nfc.dealString(),
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W400,
                        color = R.color.black_33.toComposeColor(),
                    )

                    Text(
                        text = "${item.username.dealString()} ${item.updated_time.formatTimeYMDHM()}录入",
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W400,
                        color = R.color.black_66.toComposeColor(),
                    )
                }
            }
        }
    }
}